<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" size="small" v-show="showSearch" label-width="68px">
      <el-form-item label="医生姓名" prop="doctorName">
        <el-input
          v-model="queryParams.doctorName"
          placeholder="请输入医生姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属医院" prop="hospitalId">
        <el-select v-model="queryParams.hospitalId" placeholder="请选择所属医院" @change="selectQueryDepartment" size="small">
          <el-option
            v-for="item in hospitalList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属科室" prop="departmentId">
        <el-select v-model="queryParams.departmentId" placeholder="请选择所属科室" size="small">
          <el-option
            v-for="item in departmentList"
            :key="item.id"
            :label="item.departmentName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="职称" prop="jobTitle">
        <el-select v-model="queryParams.jobTitle" placeholder="请选择职称" size="small">
          <el-option
            v-for="dict in dict.type.biz_doctor_title"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="queryParams.status" @change="handleQuery">
          <el-radio-button :label="undefined">全部</el-radio-button>
          <el-radio-button label="active">启用</el-radio-button>
          <el-radio-button label="inactive">禁用</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['biz:doctor:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['biz:doctor:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-circle-check"
          size="mini"
          :disabled="multiple"
          @click="handleBatchChangeStatus('active')"
          v-hasPermi="['biz:doctor:changeStatusBatch']"
        >批量启用
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-circle-close"
          size="mini"
          :disabled="multiple"
          @click="handleBatchChangeStatus('inactive')"
          v-hasPermi="['biz:doctor:changeStatusBatch']"
        >批量禁用
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="doctorList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="医生姓名" align="center" prop="doctorName">
        <template slot-scope="scope">
          <span style="cursor: pointer;color: #1c84c6;" @click="goDetail(scope.row)" v-hasPermi="['biz:doctor:query']">{{ scope.row.doctorName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="职称" align="center" prop="jobTitle">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.biz_doctor_title" :value="scope.row.jobTitle"/>
        </template>
      </el-table-column>
      <el-table-column label="科室" align="center" prop="departmentName"/>
      <el-table-column label="医院" align="center" prop="hospitalName"/>
      <el-table-column label="擅长" align="center" prop="goodAt" width="500px"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span v-if="scope.row.status === 'active'" style="color: green">启用</span>
          <span v-if="scope.row.status === 'inactive'" style="color: red">禁用</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center"  class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-show="scope.row.status==='inactive'"
            size="mini"
            type="text"
            icon="el-icon-check"
            style="color: #4AB7BD"
            @click="handleChangeStatus(scope.row)"
            v-hasPermi="['biz:doctor:changeStatus']"
          >启用
          </el-button>
          <el-button
            v-show="scope.row.status==='active'"
            size="mini"
            type="text"
            icon="el-icon-close"
            style="color: #E65D6E"
            @click="handleChangeStatus(scope.row)"
            v-hasPermi="['biz:doctor:changeStatus']"
          >禁用
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['biz:doctor:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document-checked"
            @click="bindingAccount(scope.row)"
            v-hasPermi="['biz:doctor:bindingUserAccount']"
          >绑定账号
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改医生对话框 -->
    <el-drawer
      :title="title"
      :visible.sync="open"
      size="50%"
      :show-close="true"
      :wrapperClosable="false"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" style="margin-left: 20px">
        <el-form-item label="医生照片" prop="doctorPhoto">
          <el-upload
            class="avatar-uploader"
            accept="image/jpeg,image/png,image/jpg"
            :action="upload.url"
            name="multipartFile"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.doctorPhoto" :src="form.doctorPhoto" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip" style="color: red">推荐上传jpg、png、jpeg文件，且不超过2MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="医生姓名" prop="doctorName">
          <el-input v-model="form.doctorName" maxlength="20" placeholder="请输入医生姓名" style="width: 70%;"/>
        </el-form-item>
        <el-form-item label="职称" prop="jobTitle">
          <el-select v-model="form.jobTitle" placeholder="请选择职称" style="width: 70%;">
            <el-option
              v-for="dict in dict.type.biz_doctor_title"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属医院" prop="hospitalId">
          <el-select v-model="form.hospitalId" placeholder="请选择所属医院" @change="selectDepartment" style="width: 70%">
            <el-option
              v-for="item in hospitalList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属科室" prop="departmentId">
          <el-select v-model="form.departmentId" placeholder="请选择所属科室" style="width: 70%">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.departmentName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="从业年限" prop="workYears">
          <el-input v-model="form.workYears" maxlength="3" placeholder="请输入从业年限"
                    oninput="value=value.replace(/[^0-9.]/g,'')" style="width: 70%"
          >
            <template slot="append">年</template>
          </el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio-button label="active">启用</el-radio-button>
            <el-radio-button label="inactive">禁用</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="擅长" prop="goodAt">
          <el-input v-model="form.goodAt" type="textarea" maxlength="255" placeholder="请输入内容" style="width: 70%;"/>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <Editor v-model="form.description" style="height: 300px;width: 95%"/>
        </el-form-item>

      </el-form>
      <div style="text-align: center;margin-top: 70px">
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>
    <el-drawer
      title="医生详情"
      :visible.sync="drawer"
      size="50%"
      :show-close="true"
      :wrapperClosable="false"
      append-to-body
    >

      <el-tabs v-model="activeName" style="margin: 20px 20px">
        <el-tab-pane label="基础信息" name="baseInfo">
          <el-form ref="form" :model="form" label-width="120px" size="mini">
            <el-row>
              <el-col :span="24">
                <el-form-item label="医生照片：">
                  <el-image :src="form.doctorPhoto" style="width: 140px;height: 130px"
                            :preview-src-list="new Array(form.doctorPhoto)"
                  ></el-image>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="医生名称：">{{ form.doctorName }}</el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="医生职称：">
                  <dict-tag :options="dict.type.biz_doctor_title" :value="form.jobTitle"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="从业年限：">{{ form.workYears }}年</el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="所属医院：">{{ form.hospitalName }}</el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="所属科室：">{{ form.departmentName }}</el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="擅长："> {{ form.goodAt }}</el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="简介" name="description">
          <el-button
            type="primary"
            style="margin-left: 85%"
            @click="handleEdit"
            v-hasPermi="['biz:doctor:edit']"
          >修改简介
          </el-button>
          <span v-html="form.description"></span>
        </el-tab-pane>
      </el-tabs>
    </el-drawer>

    <el-dialog title="绑定账号" :visible.sync="bindingAccountOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="医生账号" prop="bindingUserId">
          <el-select v-model="form.bindingUserId" placeholder="请选择医生账号" style="width: 65%" >
            <el-option
              v-for="item in doctorUserList"
              :key="item.userId"
              :label="item.nickName+ '【'+item.userName+'】'"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="bindingAccountLoading" @click="bindingAccountSubmitForm">确 定</el-button>
        <el-button @click="bindingAccountCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { listDoctor, getDoctor, delDoctor, addDoctor, updateDoctor, changeStatus,bindingUserAccount } from '@/api/biz/doctor'
import {getUserListByType } from '@/api/biz/escort'
import { getToken } from '@/utils/auth'
import { listAllHospital } from '@/api/biz/hospital'
import { getAllDepartmentListByHospital } from '@/api/biz/department'
import UEditor from '@/components/UEditor'

export default {
  name: 'Doctor',
  dicts: ['biz_doctor_title'],
  components: {
    UEditor
  },
  data() {
    return {
      activeName: 'baseInfo',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 医生表格数据
      doctorList: [],
      hospitalList: [],
      departmentList: [],
      doctorUserList:[],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      bindingAccountOpen:false,
      drawer: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        hospitalId: undefined,
        departmentId: undefined,
        doctorName: undefined,
        doctorPhoto: undefined,
        goodAt: undefined,
        jobTitle: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      submitLoading: false,
      bindingAccountLoading: false,
      // 表单校验
      rules: {
        hospitalId: [
          { required: true, message: '所属医院不能为空', trigger: 'blur' }
        ],
        departmentId: [
          { required: true, message: '所属科室不能为空', trigger: 'blur' }
        ],
        doctorPhoto: [
          { required: true, message: '医生照片不能为空', trigger: 'blur' }
        ],
        doctorName: [
          { required: true, message: '医生姓名不能为空', trigger: 'blur' }
        ],
        bindingUserId: [
          { required: true, message: '医生账号不能为空', trigger: 'blur' }
        ],
        jobTitle: [
          { required: true, message: '职称不能为空', trigger: 'blur' }
        ],
        workYears: [
          { pattern: /^[0-9]*$/, message: '从业年限需为数字', trigger: 'blur' },
          { required: true, message: '从业年限不能为空', trigger: 'blur' }
        ]

      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/common/uploadObs'
      }
    }
  },
  created() {
    this.getList()
    this.getAllHospitalList()
  },
  methods: {
    /** 查询医生列表 */
    getList() {
      this.loading = true
      listDoctor(this.queryParams).then(response => {
        this.doctorList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    getAllHospitalList() {
      listAllHospital().then(res => {
        this.hospitalList = res.data
      })
    },
    getAllDepartmentListByHospital(hospitalId) {
      getAllDepartmentListByHospital(hospitalId).then(res => {
        this.departmentList = res.data
      })
    },
    selectDepartment(val) {
      this.form.departmentId = undefined
      this.getAllDepartmentListByHospital(val)
    },
    selectQueryDepartment(val) {
      this.queryParams.departmentId = undefined
      this.getAllDepartmentListByHospital(val)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 取消按钮
    bindingAccountCancel() {
      this.bindingAccountOpen = false
      this.reset()
    },
    getIndex($index) {
      //表格序号
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + $index + 1
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        hospitalId: null,
        departmentId: null,
        doctorName: null,
        doctorPhoto: null,
        goodAt: null,
        jobTitle: null,
        status: 'active',
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null,
        description: null,
        workYears: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加医生'
    },
    handleChangeStatus(row) {
      let statusText = row.status === 'active' ? '禁用' : '启用'
      let status = row.status === 'active' ? 'inactive' : 'active'
      const ids = [row.id] || this.ids
      this.$confirm('是否确认' + statusText + '该项数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return changeStatus({ ids: ids, status: status })
      }).then(() => {
        this.getList()
        this.msgSuccess('操作成功')
      }).catch(function() {
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getDoctor(id).then(response => {
        this.form = response.data
        this.getAllDepartmentListByHospital(this.form.hospitalId)

        this.open = true
        this.title = '修改医生'
      })
    },
    /** 绑定账号操作 */
    bindingAccount(row) {
      this.reset()
      const id = row.id || this.ids
      this.getUserListByType({userType:"40"})
      getDoctor(id).then(response => {
        this.form = response.data
        this.bindingAccountOpen = true;
      })
    },
    getUserListByType(query){
      getUserListByType(query).then(res =>{
        if(res.code === 200){
          this.doctorUserList = res.data;
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.submitLoading = true
          if (this.form.id != null) {
            updateDoctor(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.submitLoading = false
              this.getList()
            }).catch(() => {
              this.submitLoading = false
            })
          } else {
            addDoctor(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.submitLoading = false
              this.getList()
            }).catch(() => {
              this.submitLoading = false
            })
          }
        }
      })
    },
    bindingAccountSubmitForm(){
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.bindingAccountLoading = true
          bindingUserAccount(this.form).then(response => {
            this.$modal.msgSuccess('绑定成功')
            this.bindingAccountOpen = false
            this.bindingAccountLoading = false
            this.getList()
          }).catch(() => {
            this.bindingAccountLoading = false
          })

        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除医生编号为"' + ids + '"的数据项？').then(function() {
        return delDoctor(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /**详情中编辑*/
    handleEdit() {
      this.drawer = false
      this.open = true
      this.title = '修改医生'
    },
    /**批量修改状态*/
    handleBatchChangeStatus(status) {
      let statusText = status === 'active' ? '启用' : '禁用'
      const ids = this.ids
      this.$confirm('是否确认' + statusText + '选中的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return changeStatus({ ids: ids, status: status })
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('操作成功')
      }).catch(function() {
      })
    },

    /**详情*/
    goDetail(row) {
      this.activeName = 'baseInfo'
      getDoctor(row.id).then(response => {
        this.form = response.data
        this.drawer = true
      })

    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('biz/doctor/export', {
        ...this.queryParams
      }, `doctor_${new Date().getTime()}.xlsx`)
    },
    handleAvatarSuccess(res, file) {
      this.form.doctorPhoto = res.data.url
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isLt2M
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.dd {
  width: 200px;
  float: left;
}

.level {
  margin-left: 17px;
  width: 80px;
  height: 35px;
  text-align: center;
  line-height: 35px;
  margin-top: 20px
}

.imageDiv {
  width: 150px;
  height: 100px;
  float: left;
  margin-left: 17px;
}
</style>
